// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;

namespace SnapObjects.Data
{
    internal abstract class SqlDeleteStatementGenerator : SqlStatementGenerator
    {
        public SqlDeleteStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }

        protected override IReadOnlyList<SqlToken> SpliceStatement(SqlStatement statement)
        {
            var result = new List<SqlToken>();

            if (statement.StatementType == SqlStatementType.Delete)
            {
                var delete = (SqlDeleteStatement)statement;

                this.ParseDelete(result, delete);

                this.ParseDeleteWhere(result, delete);
            }
            else
            {
                result.AddRange(base.SpliceStatement(statement));
            }

            return result;
        }

        protected virtual void ParseDelete(List<SqlToken> tokens, SqlDeleteStatement delete)
        {
            tokens.Add(new SqlKeywordToken(SqlKeywords.DELETE));
            tokens.Add(SqlWhitespaceToken.Whitespace);

            if (delete.From.Count > 0)
            {
                tokens.AddRange(this.SpliceClause(delete.Table));
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlKeywordToken(SqlKeywords.FROM));
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.AddRange(this.SpliceClause(delete.From));
            }
            else
            {
                tokens.Add(new SqlKeywordToken(SqlKeywords.FROM));
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.AddRange(this.SpliceClause(delete.Table));
            }
        }

        protected virtual void ParseDeleteWhere(List<SqlToken> tokens, SqlDeleteStatement delete)
        {
            if (delete.Where.Count > 0)
            {
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.Add(new SqlKeywordToken(SqlKeywords.WHERE));
                tokens.Add(SqlWhitespaceToken.Whitespace);
                tokens.AddRange(this.SpliceClause(delete.Where));
            }
        }
    }
}
